<?php

/**
 * Form input that uses regular expression to validate its data
 * @author shenlon
 */
class FormRegexInput extends FormInput {

    /**
     * Regular expression used to validate data
     * @var type 
     */
    private $regexp;

    /**
     * Default constructor
     * @param string $name
     * @param string $required
     * @param string $regexp
     * @param Array $options 
     */
    public function __construct($name, $required, $regexp, $options = null) {
        parent::__construct($name, $required, "text");
        if ($options != null)
            foreach ($options as $key => $value) {
                if (property_exists($this, $key))
                    $this->$key = $value;
                else
                    $this->optionalData[$key] = $value;
            }
        $this->regexp = $regexp;
        $htmlRegexp = substr($this->regexp, 2, -1);
        $this->optionalData["pattern"] = $htmlRegexp;
    }

    /**
     * Validates data by calling FormInput->validateData and by checking if data matches regular expression given
     * @param object $data
     * @return Array
     */
    public function validateData($data) {
        $errorMsg = "Wartość $data jest niepoprawna.";
        $errors = parent::validateData($data);
        if ($this->required == true && $data != '' && !preg_match($this->regexp, $data)) {
            if (!is_array($errors))
                $errors = array($errorMsg);
            else
                $errors[] = $errorMsg;
        }
        return $errors;
    }

}

?>
